#include "colors_classification.h"

Colors_ClassIfication::Colors_ClassIfication(QWidget *parent)
    : CommonGraphicsView{parent}
{
    this->setWindowTitle("颜色分类");
}

void Colors_ClassIfication::dropEvent(QDropEvent *event){
    QString filePath = event->mimeData()->urls().at(0).toLocalFile();
    showColorsClassification(filePath.toStdString().c_str());
}

void Colors_ClassIfication::showColorsClassification(const char *filePath){
    //输入图像
    Mat src = imread(filePath);
    if(src.empty()){
        qDebug()<<"图片为空";
        return;
    }
    imshow("src",src);
    //定义随机颜色
    Scalar colorTab[] = {
        Scalar(0,0,255),
        Scalar(0,255,0),
        Scalar(255,0,0),
        Scalar(0,255,255),
        Scalar(255,0,255)
    };
    //获取原图属性，宽高及维度
    int width = src.cols;
    int height = src.rows;
    int dims = src.channels();//通道数


    //初始化采样数量
    int sampleCount= width*height;
    int clusterCount = 4;//四分类
    Mat points(sampleCount,dims,CV_32F,Scalar(10));
    Mat labels;
    Mat centers(clusterCount,1,points.type());
    //将RGB图片数据转换为样本数据，因为kmeans要求输入的样本数据为CV_32F类型的
    int index = 0;
    for(int row = 0;row<height;row++){
        for(int col = 0;col<width;col++){
            index = row*width+col;
            Vec3b bgr = src.at<Vec3b>(row,col);
            points.at<float>(index,0) = static_cast<int>(bgr[0]);
            points.at<float>(index,1) = static_cast<int>(bgr[1]);
            points.at<float>(index,2) = static_cast<int>(bgr[2]);
        }
    }

    //使用KMeans分类
    TermCriteria criteria = TermCriteria(TermCriteria::EPS+TermCriteria::COUNT,10,0.1);
    kmeans(points,clusterCount,labels,criteria,3,KMEANS_PP_CENTERS,centers);

    //显示图像分割后的结果
    Mat result = Mat::zeros(src.size(),src.type());
    for(int row=0;row<height;row++){
        for(int col=0;col<width;col++){
            index  = row*width+col;
            int label = labels.at<int>(index,0);
            result.at<Vec3b>(row,col)[0] = colorTab[label][0];
            result.at<Vec3b>(row,col)[1] = colorTab[label][1];
            result.at<Vec3b>(row,col)[2] = colorTab[label][2];
        }
    }
    imshow("result",result);

}
